package cn.kgc.tangcco.cookie;

import cn.kgc.tangcco.utils.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/10/19 下午2:09
 */
@WebServlet(urlPatterns = {"/cookie.action","/cookie.do"})
public class CookieAction extends BaseServlet {
    private static final long serialVersionUID = 3187893360051422761L;
    public void write(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Cookie为key-value结构
        // 一般由服务器端创建 存储在客户端
        // 1、服务器创建cookie
        Cookie c1 = new Cookie("c1", "phoenix");
        Cookie c2 = new Cookie("c2", "lihaozhe");
        // URLEncode和URLDecode用于完成普通字符串和 application/x-www-from-urlencoded
        // MIME字符串之间的相互转化
        // 如果传递的字符串中包含非西欧字符的字符串，会被转化成%XX%XX XX为十六进制的数
        Cookie c3 = new Cookie("c3", URLEncoder.encode("李昊哲","utf-8"));
        Cookie c4 = new Cookie("c4", URLEncoder.encode("课工场","utf-8"));
        // 设置Cookie过期时间 单位秒
        // 设置的方式：秒 * 分 * 时 * 天
        // -1 表示立即过期，浏览器关闭后立即过期（默认）
        c2.setMaxAge(60 * 60 * 24 * 7);
        c3.setMaxAge(60 * 60 * 24 * 7);
        c4.setMaxAge(60 * 60 * 24 * 7);
        // 设置访问路径
        // c4.setDomain("www.ekgc.cn");
        c4.setPath("/hero");
        // 3、设置访问路径及客户端js是否可以操作cookie
        c4.setHttpOnly(true);
        response.addCookie(c1);
        response.addCookie(c2);
        response.addCookie(c3);
        response.addCookie(c4);
        request.getRequestDispatcher("/cookie.jsp").forward(request,response);
    }

    public void read(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("c3")||cookie.getName().equals("c4")){
                    System.out.println(cookie.getName() + " >>> " + URLDecoder.decode(cookie.getValue(),"utf-8"));
                }else{
                    System.out.println(cookie.getName() + " >>> " + cookie.getValue());
                }

            }
        }
        request.getRequestDispatcher("/cookie.jsp").forward(request,response);
    }
}
